package org.linlinjava.litemall.admin.job;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.task.ScheduledCronTaskRegistrar;
import org.linlinjava.litemall.core.constant.LitemallWXMembershipLevelConstants;
import org.linlinjava.litemall.core.notify.NoticeHelper;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LumiereLevelMember;
import org.linlinjava.litemall.db.domain.LumiereLevelMemberPoint;
import org.linlinjava.litemall.db.domain.LumiereLevelMemberPointExample;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.LumiereLevelMemberPointService;
import org.linlinjava.litemall.db.service.LumierelLevelMemberService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

import static org.linlinjava.litemall.db.beans.Constants.MEMBER_STATUS_INUSE;

/**
 * @author yliyun
 * @date 2022/09/14
 */
@Component
public class MemberJob implements Job {
    /**
     * 日志记录器
     */
    private final Log logger = LogFactory.getLog(MemberJob.class);

    /**
     *
     */
    @Autowired
    private LumiereLevelMemberPointService lumiereLevelMemberPointService;

    /**
     * litemall用户服务
     */
    @Autowired
    private LitemallUserService litemallUserService;

    /**
     * lumierel级别会员服务
     */
    @Autowired
    private LumierelLevelMemberService lumierelLevelMemberService;

    @Autowired
    private NoticeHelper noticeHelper;

    @Autowired
    private ScheduledCronTaskRegistrar scheduledCronTaskRegistrar;


    /**
     * 查看每个用户的等级是否到期，并根据条件降级
     */
    //@Scheduled(cron = "30 * * * * ?")
    //@Scheduled(cron = "30 10 * * * ?")
    @Transactional
    public void saveUserLevel() {
        logger.info("检查是否有用户触发自动降低等级会员");
        //所有存在的会员
        List<LumiereLevelMemberPoint> levelMemberPoints = lumiereLevelMemberPointService.list(Wrappers.lambdaQuery(LumiereLevelMemberPoint.class).eq(LumiereLevelMemberPoint::getDeleted, 0));
        levelMemberPoints.stream().forEach(levelMemberPoint -> {
            //查看会员是否过期
            if(levelMemberPoint.getEndTime() != null && levelMemberPoint.getEndTime().compareTo(LocalDateTime.now()) > 0){return;}
            //查看是否保级 获取当前用户的保级金额和积分
            LitemallUser user = litemallUserService.findById(levelMemberPoint.getUserId());
            if(ObjectUtil.isNull(user)){return;}
            LumiereLevelMember level = lumierelLevelMemberService.findById(user.getUserLevel().intValue());
            if(ObjectUtil.isNull(level)){return;}
            if(ObjectUtil.isNotNull(level)){
                //达到金额保级
                if(levelMemberPoint.getConsumptionMoney().compareTo(level.getSaveLevelMoney())==0||levelMemberPoint.getConsumptionMoney().compareTo(level.getSaveLevelMoney())==1){
                    return;
                }
                //达到积分保级
                if(levelMemberPoint.getConsumptionPoints().compareTo(level.getSaveLevelPoint())==0||levelMemberPoint.getConsumptionPoints().compareTo(level.getSaveLevelPoint())==1){
                    return;
                }
            }
            //已过期
            if(level.getPid() == null){return;}
            //不是最低等级,降级
            LumiereLevelMember lastLevel = lumierelLevelMemberService.findById(level.getPid());
            while (lastLevel != null && (lastLevel.getDeleted() == true || !lastLevel.getStatus().equals(MEMBER_STATUS_INUSE))) {
                lastLevel = lumierelLevelMemberService.findById(lastLevel.getPid());
            }
            if (lastLevel != null && (lastLevel.getDeleted() == false && lastLevel.getStatus().equals(MEMBER_STATUS_INUSE) == true)) {
                user.setUserLevel(lastLevel.getId().byteValue());
                levelMemberPoint.setStartTime(LocalDateTime.now());
                if (lastLevel.getExpiredDays() != null && lastLevel.getExpiredDays() != 0) {
                    levelMemberPoint.setEndTime(LocalDateTime.now().plusDays(lastLevel.getExpiredDays()));
                } else {
                    levelMemberPoint.setEndTime(null);
                }
                litemallUserService.updateById(user);
                lumiereLevelMemberPointService.update(levelMemberPoint);
                //发送降级系统通知
                noticeHelper.noticeUser(Constants.MSG_TYPE_OTHER,
                        LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_TITLE_NOTICEHELPER,
                        String.format(LitemallWXMembershipLevelConstants.WX_MEMBERSHIP_LEVEL_DEMOTION_NOTICEHELPER, lastLevel.getName()), user.getId(), lastLevel);
            }
        });



    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        this.saveUserLevel();
        scheduledCronTaskRegistrar.scheduleJobLog(jobExecutionContext);
    }
}
